package com.atguigu.tingshu.user.service.impl;

import com.atguigu.tingshu.album.client.TrackInfoFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.*;
import com.atguigu.tingshu.user.mapper.*;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.user.service.UserPaidTrackService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.LocalDateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserPaidAlbumMapper userPaidAlbumMapper;
    @Autowired
    private UserPaidTrackService userPaidTrackService;
    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;
    @Autowired
    private TrackInfoFeignClient trackInfoFeignClient;
    @Autowired
    private VipServiceConfigMapper vipServiceConfigMapper;
    @Autowired
    private UserVipServiceMapper userVipServiceMapper;

    @Override
    public UserInfoVo getUserInfoVoByUserId(Long userId) {
        UserInfo userInfo = this.getById(userId);
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        return userInfoVo;
    }

    @Override
    public Map<Long, Integer> userIsPaidTrack(Long userId, Long albumId, List<Long> trackIdList) {
        UserPaidAlbum userPaidAlbum = userPaidAlbumMapper.selectOne(new LambdaQueryWrapper<UserPaidAlbum>().eq(UserPaidAlbum::getUserId, userId)
                .eq(UserPaidAlbum::getAlbumId, albumId));
        if (null != userPaidAlbum) {
            HashMap<Long, Integer> map = new HashMap<>();
            trackIdList.forEach(trackId -> {
                map.put(trackId, 1);
            });
            return map;
        } else {
            List<UserPaidTrack> userPaidTrackList = userPaidTrackService.list(new LambdaQueryWrapper<UserPaidTrack>().eq(UserPaidTrack::getUserId, userId)
                    .in(UserPaidTrack::getTrackId, trackIdList));

            List<Long> userTrackIdList = userPaidTrackList.stream().map(UserPaidTrack::getTrackId).collect(Collectors.toList());
            HashMap<Long, Integer> map = new HashMap<>();
            trackIdList.forEach(trackId -> {
                if (userTrackIdList.contains(trackId)) {
                    map.put(trackId, 1);
                } else {
                    map.put(trackId, 0);
                }
            });
            return map;
        }

    }

    @Override
    public Boolean isPaidAlbum(Long userId, Long albumId) {
        // 根据用户Id 与专辑Id 查询是否有记录
        Long count = userPaidAlbumMapper.selectCount(new LambdaQueryWrapper<UserPaidAlbum>().eq(UserPaidAlbum::getUserId, userId).eq(UserPaidAlbum::getAlbumId, albumId));
        if (count > 0) {
            return true;
        }
        return false;
    }

    @Override
    public List<Long> findUserPaidTrackList(Long userId, Long albumId) {
        //select * from user_paid_track up where up.user_id=? and up.album_id=?
        List<UserPaidTrack> trackList = userPaidTrackMapper.selectList(new LambdaQueryWrapper<UserPaidTrack>()
                .eq(UserPaidTrack::getUserId, userId)
                .eq(UserPaidTrack::getAlbumId, albumId));

        List<Long> trackIdList = trackList.stream()
                .map(UserPaidTrack::getTrackId).collect(Collectors.toList());
        return trackIdList;
    }

    @Override
    public void savePaidRecord(UserPaidRecordVo userPaidRecordVo) {
        String itemType = userPaidRecordVo.getItemType();
        if (SystemConstant.ORDER_ITEM_TYPE_ALBUM.equals(itemType)) {
            UserPaidAlbum userPaidAlbum = userPaidAlbumMapper.selectOne(new LambdaQueryWrapper<UserPaidAlbum>()
                    .eq(UserPaidAlbum::getUserId, userPaidRecordVo.getUserId())
                    .eq(UserPaidAlbum::getOrderNo, userPaidRecordVo.getOrderNo()));
            if (userPaidAlbum != null) {//已经添加
                return;
            }
            userPaidAlbum = new UserPaidAlbum();
            userPaidAlbum.setUserId(userPaidRecordVo.getUserId());
            userPaidAlbum.setOrderNo(userPaidRecordVo.getOrderNo());
            userPaidAlbum.setAlbumId(userPaidRecordVo.getItemIdList().get(0));

            userPaidAlbumMapper.insert(userPaidAlbum);
        } else if (SystemConstant.ORDER_ITEM_TYPE_TRACK.equals(itemType)) {
//判断当前用户 + 声音记录是否添加
            LambdaQueryWrapper<UserPaidTrack> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserPaidTrack::getUserId,userPaidRecordVo.getUserId());
            wrapper.eq(UserPaidTrack::getOrderNo,userPaidRecordVo.getOrderNo());
            Long count = userPaidTrackMapper.selectCount(wrapper);
            if (count>0){
                return;
            }
            List<Long> itemIdList = userPaidRecordVo.getItemIdList();

            //没有添加，进行添加操作
            //远程调用：根据声音id获取声音对象
            Result<TrackInfo> trackInfoResult = trackInfoFeignClient.getTrackInfo(itemIdList.get(0));
            TrackInfo trackInfo = trackInfoResult.getData();
            //从声音对象里面获取专辑id
            Long albumId = trackInfo.getAlbumId();

            //所有添加声音id集合遍历，得到每个声音id，添加数据库里面
            itemIdList.stream().forEach(trackId -> {
                UserPaidTrack userPaidTrack = new UserPaidTrack();
                userPaidTrack.setTrackId(trackId);
                userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
                userPaidTrack.setUserId(userPaidRecordVo.getUserId());
                //  获取专辑Id
                userPaidTrack.setAlbumId(albumId);
                userPaidTrackMapper.insert(userPaidTrack);
            });
        } else {//购买vip记录
            //根据用户id获取用户信息
            UserInfo userInfo = userInfoMapper.selectById(userPaidRecordVo.getUserId());

            //判断当前用户状态
            //获取当前时间
            Date currentTime = new Date();

            //判断用户是vip，获取过期时间
            if(userInfo.getIsVip().intValue()==1 && userInfo.getVipExpireTime().after(new Date())) {
                currentTime = userInfo.getVipExpireTime();
            }

            //获取购买vip期限
            List<Long> itemIdList = userPaidRecordVo.getItemIdList();
            VipServiceConfig vipServiceConfig =
                    vipServiceConfigMapper.selectById(itemIdList.get(0));
            Integer serviceMonth = vipServiceConfig.getServiceMonth();

            //计算过期时间
            // currentTime + serviceMonth
            LocalDateTime localDateTime = new LocalDateTime(currentTime).plusMonths(serviceMonth);
            Date expireTime = localDateTime.toDate();

            //添加vip购买记录
            UserVipService userVipService = new UserVipService();
            userVipService.setOrderNo(userPaidRecordVo.getOrderNo());
            userVipService.setUserId(userPaidRecordVo.getUserId());
            userVipService.setStartTime(new Date());
            //--------------> 购买的时长:
            userVipService.setExpireTime(expireTime);
            //  保存
            userVipServiceMapper.insert(userVipService);

            //修改用户表vip状态数据
            //  修改user_info.is_vip=1;
            userInfo.setIsVip(1);
            //  设置过期时间
            userInfo.setVipExpireTime(expireTime);
            //  修改
            this.userInfoMapper.updateById(userInfo);
        }

    }

    @Override
    public UserInfoVo getUserInfo(Long userId) {

        UserInfo userInfo = userInfoMapper.selectById(userId);
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,userInfoVo);
        return userInfoVo;
    }

}
